package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.Date;
import java.util.Calendar;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Database.DatabaseConnector;
import ExceptionClasses.CantAccessEmailException;
import ExceptionClasses.InvalidReviewerAuthenticationException;
import Utilities.EmailClient;
/**
 * Servlet implementation class PostReviewServlet
 */
@WebServlet("/PostReviewServlet")
public class PostReviewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("in Post Review Servlet");
		HttpSession session = request.getSession();
		String business = request.getParameter("business");
		String content	= request.getParameter("content");
		DatabaseConnector db = new DatabaseConnector();

		if(business.equals("true")){
			System.out.println("it is true");
			business = (String) session.getAttribute("username");
		}
		
		System.out.println(business);
		
		try {
			EmailClient client = new EmailClient(business);
			Calendar date = Calendar.getInstance();
			Date pDate = new Date(date.getTimeInMillis());
			boolean logged = (Boolean) session.getAttribute("subloggedIn");
			if(logged){
				String userName = (String) session.getAttribute("subUser");
				String password = (String) session.getAttribute("subPass");

				if(db.authenticateReviewer(userName, password))
				{
					try {
						System.out.println("adding review");
						db.addReview(userName, password, business, content, pDate);
						try {
							System.out.println("emailing client");
							client.updateSubscribers(content);
							response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
						} catch (MessagingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
						}
					} catch (InvalidReviewerAuthenticationException e) {
					// TODO Auto-generated catch block
						e.printStackTrace();
						response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
					}
				}
			}
			else{
				System.out.println("Can't post review");
				response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
			}
			
		} catch (CantAccessEmailException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
		response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
	}
}
